import 'dart:convert';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/ui/Home/activity/sign_up/act_sign_up_list.dart';
import 'package:fate_blind_box/ui/Home/activity/sign_up/web_details_content_page.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/utils/loading.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../../cooperation/activity/publish/act_publish_bottom_view.dart';
import 'act_details_controller.dart';
import 'act_details_model.dart';
import 'act_list_model.dart';
import 'package:vsc_quill_delta_to_html/vsc_quill_delta_to_html.dart';

class ActDetailsPage extends StatefulWidget {
  String? actId = '';
  FuturePopular? dataModel;

  ActDetailsPage({required this.actId, this.dataModel, Key? key})
      : super(key: key);

  @override
  State<ActDetailsPage> createState() => _ActDetailsPageState();
}

class _ActDetailsPageState extends State<ActDetailsPage> {
  ActDetailsController detailsController = Get.put(ActDetailsController());
  FocusNode focusNode = FocusNode();

  @override
  Widget build(BuildContext context) {
    return AppWidget.navTitleBar(
      title: '相亲活动',
      childWidget: GetBuilder(
          id: detailsController.detailsViewId,
          builder: (ActDetailsController controller) {
            String actiCover = widget.dataModel!.actiCover ?? '';
            ActDetailsDataModel detailsModel = controller.detailsModel;
            int signNum = widget.dataModel!.sign ?? 0;
            String signName = detailsController.getSignStatus(signNum);
            String actiDescribe =
                getHtmlFromDelta(detailsModel.actiDescribe ?? '');
            return Column(
              children: [
                Expanded(
                  child: NestedScrollView(
                      headerSliverBuilder:
                          (BuildContext context, bool innerBoxIsScrolled) {
                        return [
                          SliverToBoxAdapter(
                            child: Stack(
                              children: [
                                Column(
                                  children: [
                                    actiCover.isEmpty
                                        ? Container()
                                        : Image.network(
                                            actiCover,
                                            height: 205.w,
                                            width: 1.sw,
                                            fit: BoxFit.cover,
                                          ),
                                    SizedBox(
                                      height: 136.w,
                                    ),
                                    Padding(
                                      padding: const EdgeInsets.symmetric(horizontal: 14),
                                      child: Row(
                                        children: [
                                          Text(
                                            '已报名（${detailsModel.enrollNum}）',
                                            style: TextStyle(
                                                fontSize: 16,
                                                color: ThemeColor.black3D3D3DColor,
                                                fontWeight: FontWeight.w500),
                                          ),
                                          Expanded(child: Container()),
                                          GestureDetector(
                                            onTap: () {
                                              Get.to(ActSignUpListPage(
                                                actId: widget.actId ?? '',
                                              ));
                                            },
                                            child: Row(
                                              mainAxisAlignment: MainAxisAlignment.end,
                                              children: [
                                                Text(
                                                  '查看更多',
                                                  style: TextStyle(
                                                    fontSize: 14,
                                                    color: ThemeColor.gray4C4C4CColor,
                                                  ),
                                                ),
                                                Icon(
                                                  Icons.arrow_forward_ios,
                                                  size: 16,
                                                  color: ThemeColor.gray4C4C4CColor,
                                                )
                                              ],
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                    SizedBox(
                                      height: 15.w,
                                    ),
                                    Padding(
                                      padding: EdgeInsets.symmetric(horizontal: 14.w),
                                      child: SizedBox(
                                        width: 1.sw,
                                        child: Wrap(
                                          alignment: WrapAlignment.start,
                                          spacing: 18.w,
                                          children: getEnrollList(),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                                Positioned(
                                    left: 14,
                                    right: 14,
                                    top: 146 + ScreenUtil().statusBarHeight,
                                    child: Container(
                                      padding:
                                      const EdgeInsets.only(left: 14, top: 14, bottom: 16),
                                      decoration: BoxDecoration(
                                        color: Colors.white,
                                        borderRadius: BorderRadius.circular(5),
                                        boxShadow: const [
                                          BoxShadow(
                                              color: Color.fromRGBO(0, 0, 0, 0.1),
                                              blurRadius: 10,
                                              blurStyle: BlurStyle.outer,
                                              offset: Offset(0, 2))
                                        ],
                                      ),
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Text(
                                            widget.dataModel?.actiTitle ?? '',
                                            style: TextStyle(
                                                fontSize: 16,
                                                color: ThemeColor.black3D3D3DColor),
                                          ),
                                          const SizedBox(
                                            height: 14,
                                          ),
                                          Row(
                                            children: [
                                              Image.asset(
                                                'images/scan/details_time_clock.png',
                                                width: 14,
                                              ),
                                              const SizedBox(
                                                width: 2,
                                              ),
                                              Text(
                                                detailsModel.actiTime ?? '',
                                                style: TextStyle(
                                                    color: ThemeColor.gray99A3B4Color,
                                                    fontSize: 14),
                                              )
                                            ],
                                          ),
                                          const SizedBox(
                                            height: 14,
                                          ),
                                          Row(
                                            children: [
                                              Image.asset(
                                                'images/scan/details_map_location.png',
                                                width: 14,
                                              ),
                                              const SizedBox(
                                                width: 2,
                                              ),
                                              Text(
                                                '${detailsModel.actiProvince}${detailsModel.actiCity}${detailsModel.actiArea}${detailsModel.actiAddr}',
                                                style: TextStyle(
                                                    color: ThemeColor.gray99A3B4Color,
                                                    fontSize: 14),
                                              ),
                                            ],
                                          ),
                                          const SizedBox(
                                            height: 14,
                                          ),
                                          Row(
                                            children: [
                                              Image.asset(
                                                'images/scan/deails_money_type.png',
                                                width: 14,
                                              ),
                                              const SizedBox(
                                                width: 2,
                                              ),
                                              Text(
                                                widget.dataModel!.actiCost ?? '',
                                                style: TextStyle(
                                                    color: ThemeColor.redE84D46Color,
                                                    fontSize: 14),
                                              ),
                                            ],
                                          ),
                                        ],
                                      ),
                                    )),
                              ],
                            ),
                          ),
                        ];
                      },
                      body: SizedBox(
                        height: 200,
                        width: 1.sw - 15 * 2,
                        child: actiDescribe.isNotEmpty
                            ? WebDetailsContentPage(url: actiDescribe)
                            : Container(),
                      )),
                ),
                ActPubLishBottomView(
                  isHiddenLeftAction: true,
                  leftName: '分享',
                  rightName: detailsController.getSignStatus(signNum),
                  rightColor: signNum == 1
                      ? ThemeColor.appColor
                      : ThemeColor.checkNormalColor,
                  rightAction: () {
                    if (signNum == 1) {
                      showBottomSignUpDialog(detailsModel.actiPhone);
                    } else {
                      String desStr = '该活动' + signName + '，不能再进行报名';
                      toast(desStr);
                    }
                  },
                ),
              ],
            );
          }),
    );
  }

  showBottomSignUpDialog(String? mobileStr) {
    double cornerRadius = 10;
    return showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Container(
            decoration: BoxDecoration(
              shape: BoxShape.rectangle,
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(cornerRadius),
                  topRight: Radius.circular(cornerRadius)),
              color: Colors.white,
            ),
            child: Column(
              children: [
                GestureDetector(
                  onTap: () {
                    Navigator.pop(context);
                  },
                  child: Padding(
                    padding: const EdgeInsets.only(top: 21, right: 14),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Image.asset(
                          'images/scan/details_sign_close.png',
                          width: 20,
                          height: 20,
                        ),
                      ],
                    ),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    resignFirstResponse();
                  },
                  child: Container(
                    color: Colors.white,
                    padding: const EdgeInsets.symmetric(horizontal: 15),
                    child: Column(
                      children: [
                        Text(
                          '报名信息',
                          style: TextStyle(
                              fontSize: 16, color: ThemeColor.black1C1C1CColor),
                        ),
                        const SizedBox(
                          height: 14,
                        ),
                        Row(
                          children: [
                            Text(
                              '手机',
                              style: TextStyle(
                                  fontSize: 16,
                                  color: ThemeColor.grayA0A0A0Color),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
                const SizedBox(
                  height: 11,
                ),
                Container(
                  width: 1.sw - 15 * 2,
                  height: 45,
                  decoration: BoxDecoration(
                      color: ThemeColor.blueF6F8FAColor,
                      borderRadius: BorderRadius.circular(5)),
                  alignment: Alignment.center,
                  padding: const EdgeInsets.symmetric(horizontal: 10),
                  child: TextField(
                    controller: detailsController.inputController,
                    inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                    focusNode: focusNode,
                    keyboardType: TextInputType.phone,
                    decoration: const InputDecoration(
                      border: InputBorder.none,
                      isCollapsed: true,
                      hintText: '请输入手机号',
                      hintStyle: TextStyle(fontSize: 13),
                    ),
                  ),
                ),
                const SizedBox(
                  height: 13,
                ),
                Container(
                  height: 0.5,
                  color: ThemeColor.lineColor,
                ),
                const SizedBox(
                  height: 6,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    GestureDetector(
                      onTap: () {
                        resignFirstResponse();
                        String phoneStr =
                            detailsController.inputController.text;
                        if (phoneStr.isEmpty) {
                          toast('请输入手机号');
                          return;
                        }
                        if (phoneStr.length != 11) {
                          toast('请输入正确手机号');
                          return;
                        }
                        detailsController.addSignUpAction(
                            actId: widget.actId ?? '', phoneStr: phoneStr);
                      },
                      child: Container(
                        margin: const EdgeInsets.only(right: 14),
                        padding: const EdgeInsets.symmetric(
                            vertical: 12, horizontal: 53),
                        decoration: BoxDecoration(
                            color: ThemeColor.appColor,
                            borderRadius: BorderRadius.circular(5)),
                        child: const Text(
                          '我要报名',
                          style: TextStyle(color: Colors.white, fontSize: 16),
                        ),
                      ),
                    ),
                  ],
                )
              ],
            ),
          );
        });
  }

  //取消第一响应
  void resignFirstResponse() {
    if (focusNode.hasFocus) {
      focusNode.unfocus();
    }
  }

  @override
  void initState() {
    super.initState();
    widget.dataModel ??= FuturePopular();
    detailsController.getDetailsData(widget.actId ?? '');
  }

  String getHtmlFromDelta(String jonsStr) {
    String html = '';
    if (jonsStr.isNotEmpty) {
      try {
        if (jonsStr.contains('[')) {
          var myJSON = jsonDecode(jonsStr).cast<Map<String, dynamic>>();
          List<Map<String, dynamic>> jsonMap =
              myJSON as List<Map<String, dynamic>>;
          final converter = QuillDeltaToHtmlConverter(
            jsonMap,
            ConverterOptions.forEmail(),
          );

          html = converter.convert();
        } else {
          html = jonsStr;
        }
        print(html);
      } catch (e) {
        print(e);
      }
    }
    return html;
  }

  List<Widget> getEnrollList() {
    detailsController.detailsModel.joinList ??= [];
    return List.generate(detailsController.detailsModel.joinList!.length,
        (index) {
      JoinList item = detailsController.detailsModel.joinList![index];
      String profilePhoto = item.profilePhoto ?? '';
      return AppWidget.blurFixImage(
          url: profilePhoto,
          sign: detailsController.detailsModel.sign ?? 0,
          sigmaNum: 1.5);
    });
  }
}
